package com.neulogistics.contrib.transfercenter.api.application.rpc;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.neulogistics.contrib.transfercenter.domain.model.valueobject.Address;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class GeographyService implements IGeographyService {

    @Data
    class ResultItem{
        int origin_id;
        int dest_id;
        int distance;
        int duration;
    }

    @Override
    public Integer getShortestDistanceIndex(List<String> originsList, String destination) {
        // 调用接口，获得结果集
        HttpRequest request = HttpUtil.createGet("https://restapi.amap.com/v3/distance");
        String origins = originsList.stream().collect(Collectors.joining("|"));
        request.form("origins", origins)
                .form("destination", destination)
                .form("type", 0)    // 直线距离
                .form("key", System.getenv("AMAP_API_KEY"));

        HttpResponse response = request.execute();

        if (!response.isOk()){
            return null;
        }

        // 获取结果集
        String body = response.body();
        JSONObject bodyJson = JSONUtil.parseObj(body);
        JSONArray results = bodyJson.getJSONArray("results");
        List<ResultItem> resultItems = results.toList(ResultItem.class);
        Optional<ResultItem> min = resultItems.stream()
                .min(Comparator.comparingInt(ResultItem::getDistance));

        return min.isPresent()?
                min.get().origin_id - 1 : null;
    }

    @Override
    public String getLocation(Address address) {
        // 调用接口，获得经纬度
        HttpRequest request = HttpUtil.createGet("https://restapi.amap.com/v3/geocode/geo");
        request.form("address", address.getAddressString())
                .form("city", address.getCity())
                .form("key", System.getenv("AMAP_API_KEY"));

        HttpResponse response = request.execute();

        if (!response.isOk()){
            return null;
        }

        // 获取经纬度
        String body = response.body();
        JSONObject bodyJson = JSONUtil.parseObj(body);
        JSONArray geocodes = bodyJson.getJSONArray("geocodes");
        Object location = geocodes.getJSONObject(0).get("location");

        return location.toString();
    }

}

